function XBarAfk_OnUpdate(this)
	if (XBar["AfkAuto"]==true and XBar["Afk"]<1) then
		local diff=GetTime()-this.timer;
		if (diff>=XBar["AfkTimer"]) then
			XBar["Afk"]=1;
			ChatFrame1:AddMessage(XLng["Chat"]["AfkGo1"]..diff..XLng["Chat"]["AfkGo2"],1,0,0);
		end
	end
	if (XBar["Afk"]>=1) then
		if (XBar["Afk"]==1) then XBarAfk_Logo_Text:SetText("|cff76FF00[AFK]|r"); end
		if (XBar["Afk"]==2) then XBarAfk_Logo_Text:SetText("|cffFFFF00[DnD]|r"); end
		XBarAfk_Logo:Show();
	else XBarAfk_Logo:Hide(); end
end

function XBarAfk_OnEvent(this,event)
-- ChatFrame1:AddMessage("XBar-Afk : "..event);
	if (event=="LOADING_END") then
		this:RegisterEvent("CHAT_MSG_WHISPER");
		this:RegisterEvent("UPDATE_MOUSE_LEAVE");
		this:RegisterEvent("UPDATE_MOUSEOVER_UNIT");
		this.timer=GetTime();
		if (XBar["AfkEnable"]==false) then this:Hide(); end
		if (XBar["AfkKeepMsg"]==false) then XBar["AfkMsg"]={}; end
		if (XBar["AfkMind"]==false) then XBar["Afk"]=0; end
	end
	if (event=="CHAT_MSG_WHISPER" and XBar["Afk"]>0) then
		local msg=string.format(getglobal("CHAT_WHISPER_GET"),arg2);
		local value={["time"]=os.date("%H:%M.%S"),["date"]=os.date("%m.%b %y"),["name"]=arg4,["text"]=arg1};
		table.insert(XBar["AfkMsg"],1,value);
		SendChatMessage(XBar["AfkV"..XBar["Afk"]],"WHISPER",0,arg4);
		if (#XBar["AfkMsg"]>100) then table.remove(XBar["AfkMsg"],101); end
		XBarAfk_AddMsg("NEW_MSG");
	end
	if (event=="UPDATE_MOUSEOVER_UNIT" or event=="UPDATE_MOUSE_LEAVE") then
		this.timer=GetTime();
	end
end
 
function XBarAfk_OnScroll(this,delta)
	if (delta<0) then this:ScrollDown(); end
	if (delta>0) then this:ScrollUp(); end
end

function XBarAfk_AddMsg(v)
	local x=1;
	local text="";
	if (v=="INIT") then x=#XBar["AfkMsg"]; end
	for i=x,1,-1 do
		text="|cffC7C700"..XBar["AfkMsg"][i]["date"].." @ "..XBar["AfkMsg"][i]["time"].."|r ";
		text=text.."|cffEC78DC|Hplayer:"..XBar["AfkMsg"][i]["name"].."|h["..XBar["AfkMsg"][i]["name"].."]|h|r ";
		text=text.."\n"..XBar["AfkMsg"][i]["text"].."\n";
		XBarAfk_MsgFrame:AddMessage(text,.96,.96,.96);
	end
end

function XBarAfk_Toggle(key)
	if (key=="LBUTTON") then
		if (IsShiftKeyDown()) then
			if (XBarAfk:IsVisible()) then XBarAfk:Hide(); else XBarAfk:Show(); end
		elseif (XBar["Afk"]==0) then XBar["Afk"]=1;
		elseif (XBar["Afk"]==1) then XBar["Afk"]=2;
		elseif (XBar["Afk"]==2) then XBar["Afk"]=0;
			if (XBar["AfkKeepMsg"]==false) then XBar["AfkMsg"]={}; end;
		end
	end
end
